import React, { useRef, memo, useEffect, useState } from 'react';
import { Row, Col, Form, Button, MessagePlugin, Select, Input } from 'tdesign-react';
import { RESERVATION_STATUS_OPTIONS, RESERVATION_SORT_BY_OPTIONS, RESERVATION_SORT_ORDER_OPTIONS } from '../consts';
import { FormInstanceFunctions, SubmitContext } from 'tdesign-react/es/form/type';
import { useLocation, useNavigate } from 'react-router-dom';
import PubSub from 'pubsub-js'

const { FormItem } = Form;
export type FormValueType = {
  searchText?: string;
  status?: string;
  sortBy?: string;
  sortOrder?: string;
};

export type SearchFormProps = {
  onCancel: () => void;
  onSubmit: (values: FormValueType) => void;
};

const SearchForm: React.FC<SearchFormProps> = (props) => {
  const formRef = useRef<FormInstanceFunctions>();
  const location = useLocation();
  const navigate = useNavigate();
  const [path, setPath] = useState<string>('');
  // 订阅当前的路由
  PubSub.subscribe('listPath', (msg, data) => {
    setPath(data)
  });

  // 解析 URL 中的查询参数
  const getQueryParams = () => {
    const params = new URLSearchParams(location.search);
    return {
      searchText: params.get('searchText') || '',
      status: params.get('status') || '',
      sortBy: params.get('sortBy') || '',
      sortOrder: params.get('sortOrder') || '',
    };
  };

  // 初始化时从 URL 回显查询参数到表单
  useEffect(() => {
    const queryParams = getQueryParams();
    formRef.current?.setFieldsValue?.(queryParams);
  }, [location.search]);

  // 提交时同步参数到 URL
  const onSubmit = (e: SubmitContext) => {
    if (e.validateResult === true) {
      const formValues = formRef.current?.getFieldsValue?.(true) || {};

      // 构建查询字符串
      const params = new URLSearchParams();
      Object.entries(formValues).forEach(([key, value]) => {
        if (value) {
          params.set(key, value as string);
        }
      });

      // 更新 URL，不刷新页面
      navigate({ search: params.toString() }, { replace: true });

      // 调用父组件的 onSubmit
      props.onSubmit(formValues as FormValueType);
      MessagePlugin.success('查询成功');
    }
  };

  // 重置时清空 URL 参数
  const onReset = () => {
    formRef.current?.reset();
    navigate({ search: '' }, { replace: true });
    props.onCancel();
    MessagePlugin.success('重置成功');
  };

  return (
    <div className='list-common-table-query'>
      <Form ref={formRef} onSubmit={onSubmit} onReset={onReset} labelWidth={80} colon>
        <Row>
          <Col flex='1'>
            <Row gutter={[12, 12]}>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='搜索' name='searchText'>
                  <Input placeholder='请输入学号/姓名' style={{ width: '100%' }} />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='状态' name='status'>
                  <Select options={RESERVATION_STATUS_OPTIONS} placeholder='请选择状态' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序依据' name='sortBy'>
                  <Select options={RESERVATION_SORT_BY_OPTIONS} placeholder='请选择排序依据' />
                </FormItem>
              </Col>
              <Col span={4} xs={12} sm={6} xl={3}>
                <FormItem label='排序方式' name='sortOrder'>
                  <Select options={RESERVATION_SORT_ORDER_OPTIONS} placeholder='请选择排序方式' />
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col flex='280px'>
            <Button theme='primary' type='submit' style={{ margin: '0px 20px' }}>
              查询
            </Button>
            <Button type='reset' variant='base' theme='default' style={{ position: "relative", margin: '0px 20px 0 0' }}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default memo(SearchForm);